package com.guqinghan.guqinghan_11_mv_1;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    private SurfaceView surfaceView;
    private MediaPlayer player;
    private int currentPosition = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        surfaceView = findViewById(R.id.sufaceView);
        SurfaceHolder holder = surfaceView.getHolder();
        // 事件回调
        holder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                // surfaceView被创建
                player = new MediaPlayer();
                player.setDisplay(holder);
                try {
                    player.setDataSource("/sdcard/Movies/绝世极品.mp4");
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // 预加载
                player.prepareAsync();
                player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        if(currentPosition!=0){
                            // 跳到此位置
                            player.seekTo(currentPosition);
                        }
                        player.start();
                    }
                });

            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                // surfaceView被改变
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                // surfaceView被销毁
                if (player.isPlaying()){
                    // 记录一下位置
                     currentPosition = player.getCurrentPosition();
                    player.stop();
                    player.release();
                }
            }
        });
    }

    public void startVideoActivity(View view) {
        startActivity(new Intent(MainActivity.this,VideoviewActivity.class));
    }
}
